package com.example.springfortestspace.service;

import antlr.StringUtils;
import com.example.springfortestspace.LogUtil;
import com.example.springfortestspace.dao.TestSpaceDao;
import com.example.springfortestspace.entity.Customer;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @Auther：FKM
 * @Date：2024/5/3015:23
 */
@Component
@EnableScheduling
public class SchedulTaskService {
    /**
     * 定时触发方法
     */
    @Autowired
    private TestSpaceDao testSpaceDao;
    // 每隔三天执行一次任务，指定cron表达式为：0 0 0 */3 * *
   // @Scheduled(cron = "0 0 0 */3 * *")
    @Scheduled(cron = "0 0 0 */3 * *")
    public void runTask() {
        LogUtil.WriteToLogFile("开始执行定时任务=======");
        try {
            // 这里是你需要执行的任务逻辑
            Customer customer = new Customer();
            List<Customer> all = testSpaceDao.findAll(customer);
            for (Customer cus :
                    all) {
                if (!("标准222".equals(cus.getCustomName()) || "标准223".equals(cus.getCustomName()))) { //标准环境不需要删除状态
                    // 当前系统时间
                    LocalDateTime now = LocalDateTime.now();

                    // 指定的时间
                    String dateTimeStr = cus.getUpdateDate();
                    // 移除可能存在的毫秒部分
                    if (dateTimeStr.contains(".")) {
                        dateTimeStr = dateTimeStr.split("\\.")[0];
                    }
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    LocalDateTime specifiedDateTime = LocalDateTime.parse(dateTimeStr, formatter);

                    // 计算时间差
                    Duration duration = Duration.between(specifiedDateTime,now);
                    // 获取时间差的各个部分
                    long days = duration.toDays();
                    long hours = duration.toHours() % 24;
                    long minutes = duration.toMinutes() % 60;
                    long seconds = duration.getSeconds() % 60;

                    // 输出时间差
                    System.out.println("时间差为: " + days + " 天 " + hours + " 小时 " + minutes + " 分钟 " + seconds + " 秒");

                    if(days >= 3){
                        //关闭对应的项目环境
                        String serverPort = cus.getServerPort();
                        String runProcessPID = getRunProcessPID(serverPort);
                        if(!StringUtil.isNullOrEmpty(runProcessPID)){
                            Process killProcess = Runtime.getRuntime().exec("kill "+runProcessPID);
                            int i = killProcess.waitFor();
                            if(i == 0){
                                LogUtil.WriteToLogFile("客户"+cus.getCustomName()+"服务关闭完成");
                            }else{
                                LogUtil.WriteToLogFile("客户"+cus.getCustomName()+"服务关闭失败");
                            }
                            //修改状态为关闭
                            cus.setStatus("1");//停止了
                            testSpaceDao.updateIntoTableStatus(cus);
                            //关闭之后清除对应的Redis数据
                            clearnRedis(cus.getRedisDBname());


                        }else{ //如果表中状态是启动，但是实际端口并没有被占用，则更新表中数据
                            //防止有人手动关了项目
                            cus.setStatus("1");//停止了
                            testSpaceDao.updateIntoTableStatus(cus);
                        }

                    }

                }

            }
        }catch(Exception e){
            LogUtil.WriteToLogFile("当前数据清除出现错误"+e.getMessage());
            return;
        }

    }

    private void clearnRedis(String redisDBname) {
        // Redis 服务器地址
        String host = "127.0.0.1"; //本地的redis库
        // Redis 服务器端口
        int port = 6380;
        // Redis 密码
        String password = "zhilink.com";
        // Redis 数据库索引
        int dbIndex = Integer.parseInt(redisDBname);

        // 创建 Jedis 连接
        Jedis jedis = new Jedis(host, port);
        jedis.auth(password);

        // 选择数据库
        jedis.select(dbIndex);

        // 清空 Redis 数据库
        jedis.flushDB();

        // 关闭连接
        jedis.close();
    }

    public String getRunProcessPID(String port){
        String pid = "";
        try {
            //关闭对应的项目环境
            ProcessBuilder processBuilder = new ProcessBuilder();
            Process process = Runtime.getRuntime().exec("lsof -t -i :" + port);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("PID of process using port " + port + ": " + line);
                pid = line;
            }
            process.waitFor();
            process.destroy();


        }catch(Exception e){
            e.printStackTrace();
            LogUtil.WriteToLogFile("定时任务获取PID失败"+e.getMessage());
        }
        return pid;
    }

}
